<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */

class Default_Model_ProductKey extends Zend_Db_Table{
	
	protected $_name    = "product_keys";
    protected $_primary = "id";
    
    public function getKeys($order_id){
    	if($this->checkExists($order_id)){
    	    $db = Zend_Registry::get('db');
            $db->setFetchMode(Zend_Db::FETCH_OBJ);
            
            $select = $db->select()
                        ->from(array('od' => 'order_details'), array('product_id', 'quantity'))
                        ->join(array('p' => 'products'), "p.id = od.product_id", array('name'))
                        ->where('od.order_id = ?', $order_id);
            
            $products = $db->fetchAll($select);
            
            $result = array();
            
            foreach($products as $product){
                $result['product_id'] = $product->product_id;
            }
            
            $result = $db->fetchAll($select);
            
            return $result;
    	}
    }
    
    public function getKey($product_id, $quantity){
    	if($this->checkExists($order_id)){
    	    $db = Zend_Registry::get('db');
            $db->setFetchMode(Zend_Db::FETCH_OBJ);
            
            $select = $db->select()
                        ->from(array('pk' => 'product_keys'), array('id', 'product', 'key'))
                        ->where('pk.product = ?', $product_id)
                        ->where('pk.is_used = 0')
                        ->limit($quantity);
            
            $result = $db->fetchAll($select);
            
            
            
            return $result;
    	}
    }
    
    public function saveData($data, $items){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $db->insert('orders', $data);
            
            $id = $db->lastInsertId("orders");
            
            foreach($items as $item){
                $item['order_id'] = $id;
                $item['product_id'] = $item['id'];
                
                unset($item['id']);
                
                $db->insert('order_details', $item);
            }
            
            $db->commit();
            
            return $id;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function checkExists($id){
        $option = array('table' => 'orders', 'field' => 'id');
    	$validator = new Zend_Validate_Db_RecordExists($option);
        
        if($validator->isValid($id)){
            return true;
        }
        
        return false;
    }
}